import { useState, useEffect } from 'react';
import { Layout, Button, Menu, Tag } from 'antd';
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
  HomeOutlined,
  UsergroupAddOutlined,
  ShoppingCartOutlined,
  SettingOutlined,
  CloseOutlined
} from '@ant-design/icons';
import '../css/Layout.css';

const { Header, Sider, Content } = Layout;

// 菜单配置数据
const menuItems = [
  { key: '1', label: '首页', path: '/', icon: <HomeOutlined /> },
  { key: '2', label: '用户管理', path: '/users', icon: <UsergroupAddOutlined /> },
  { key: '3', label: '产品管理', path: '/products', icon: <ShoppingCartOutlined /> },
  { key: '4', label: '系统设置', path: '/settings', icon: <SettingOutlined /> },
  { key: '5', label: '待办事项', path: '/todlist', icon: <SettingOutlined /> },
];

const AppLayout = () => {
  const [collapsed, setCollapsed] = useState(false);
  // 初始化时直接包含首页，避免重复添加
  const [visitedMenus, setVisitedMenus] = useState([menuItems[0]]);
  const location = useLocation();
  const navigate = useNavigate();

  const toggle = () => {
    setCollapsed(!collapsed);
  };

  // 根据路径获取菜单信息
  const getMenuByPath = (path) => {
    return menuItems.find(item => item.path === path);
  };

  // 修复：添加依赖项并优化判断逻辑，防止重复添加
  useEffect(() => {
    const currentMenu = getMenuByPath(location.pathname);
    // 只有当当前菜单存在且不在已访问列表中时才添加
    if (currentMenu && !visitedMenus.some(item => item.key === currentMenu.key)) {
      setVisitedMenus(prev => [...prev, currentMenu]);
    }
  }, [location.pathname, visitedMenus]); // 添加依赖项，避免不必要的执行

  // 处理菜单点击
  const handleMenuClick = (key) => {
    const menu = menuItems.find(item => item.key === key);
    if (menu) {
      // 避免重复添加
      if (!visitedMenus.some(item => item.key === key)) {
        setVisitedMenus(prev => [...prev, menu]);
      }
      navigate(menu.path);
    }
  };

  // 关闭访问记录
  const handleCloseTag = (key, e) => {
    e.preventDefault();
    const newVisitedMenus = visitedMenus.filter(item => item.key !== key);
    setVisitedMenus(newVisitedMenus);

    // 如果关闭的是当前页面，跳转到最后一个访问记录或首页
    if (getMenuByPath(location.pathname)?.key === key) {
      if (newVisitedMenus.length > 0) {
        navigate(newVisitedMenus[newVisitedMenus.length - 1].path);
      } else {
        navigate('/');
      }
    }
  };

  // 获取当前选中的菜单key
  const getSelectedKey = () => {
    const menu = getMenuByPath(location.pathname);
    return menu ? menu.key : '1';
  };

  return (
    <Layout className="app-layout">
      <Sider trigger={null} collapsible collapsed={collapsed} className="menu-sider">
        <div className="sider-header">
          <h2 className={`sider-title ${collapsed ? 'hidden' : ''}`}>后台管理系统</h2>
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[getSelectedKey()]}
          className="sider-menu"
          onClick={({ key }) => handleMenuClick(key)}
        >
          {menuItems.map(item => (
            <Menu.Item key={item.key} icon={item.icon}>
              <Link to={item.path}>{item.label}</Link>
            </Menu.Item>
          ))}
        </Menu>
      </Sider>
      <Layout className="site-layout">
        <Header className="top-header">
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={toggle}
          />

          {/* 访问过的菜单标签区域 */}
          <div className="visited-tags">
            {visitedMenus.map(menu => (
              <Tag
                key={menu.key}
                closable={menu.key !== '1'} // 首页不可关闭
                onClose={(e) => handleCloseTag(menu.key, e)}
                className={getSelectedKey() === menu.key ? 'active-tag' : ''}
                onClick={() => navigate(menu.path)}
              >
                {menu.label}
                {menu.key !== '1'}
              </Tag>
            ))}
          </div>

          <div className="user-info">
            <UserOutlined />
            <span className="user-name">管理员</span>
          </div>
        </Header>
        <Content className="content-area">
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
};

export default AppLayout;
